using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NorthwindWeb.Models;

namespace NorthwindWeb.Controllers
{   
    public class SupplierController : Controller
    {
		private readonly ISupplierRepository supplierRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public SupplierController() : this(new SupplierRepository())
        {
        }

        public SupplierController(ISupplierRepository supplierRepository)
        {
			this.supplierRepository = supplierRepository;
        }

        //
        // GET: /Supplier/

        public ViewResult Index()
        {
            return View(supplierRepository.AllIncluding(supplier => supplier.Products));
        }

        //
        // POST: /Supplier/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "SupplierID")]Supplier supplier)
        {
            if (ModelState.IsValid) {
                supplierRepository.InsertOrUpdate(supplier);
                supplierRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Supplier/Edit/5

        [HttpPost]
        public ActionResult Edit(Supplier supplier)
        {
            if (ModelState.IsValid) {
                supplierRepository.InsertOrUpdate(supplier);
                supplierRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Supplier/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            supplierRepository.Delete(id);
            supplierRepository.Save();

            return RedirectToAction("Index");
        }

        
        public JsonResult supplierGridData(int rows, int page)
        {
        	var count = supplierRepository.All.Count();
            var pageData = supplierRepository.All.OrderBy(x => x.SupplierID).Skip((page - 1) * rows).Take(rows).Select(o => new {SupplierID = o.SupplierID, CompanyName = o.CompanyName, ContactName = o.ContactName, ContactTitle = o.ContactTitle, Address = o.Address, City = o.City, Region = o.Region, PostalCode = o.PostalCode, Country = o.Country, Phone = o.Phone, Fax = o.Fax, HomePage = o.HomePage});
            return Json(new { 
            page = page,
            records = count,
            rows = pageData,
            total = Math.Ceiling((decimal)count / rows)
            }, JsonRequestBehavior.AllowGet);
        }
        
        
    }
}

